package com.jvyou.jdbc;

import java.sql.*;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/17 17:00
 * @Description 主键回显
 */
public class PrimaryKeyEcho {

    public static void main(String[] args) throws SQLException {
        String url = "jdbc:mysql://localhost:3306/jvyou-mybatis";
        String username = "root";
        String password = "123456";
        Connection connection = DriverManager.getConnection(url, username, password);
        String sql = "insert into user values (?,?,?,?)";
        // 获取PreparedStatement对象时候，通过`RETURN_GENERATED_KEYS`常量指定要回显主键
        PreparedStatement psm = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        psm.setInt(1, 1001);
        psm.setString(2, "jvyou");
        psm.setString(3, "123456");
        psm.setString(4, "jvyou@jvyou.com");
        psm.executeUpdate();

        // 回显的结果是一个单行单列的 ResultSet
        ResultSet rs = psm.getGeneratedKeys();
        if (rs.next()) {
            System.out.println("主键是：" + rs.getInt(1));
        }

        psm.close();
        connection.close();
    }
}
